<?php

declare (strict_types=1);

namespace app\admin\model\admin;

use app\common\model\admin\OperationLog as OperationLogModel;
use think\db\exception\DbException;
use think\Paginator;

/**
 * 操作日志记录表模型
 * Class OperationLog
 * @package app\admin\model\admin
 */
class OperationLog extends OperationLogModel
{
    /**
     * 获取列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->with(['admin_user'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->paginate($param['pageSize'] ?? 10);
        return $list;
    }

    public function getLogTypeGroupList(){
        $query = $this->getNewQuery();
        // 查询参数
        // 查询列表记录
        $list = $query
            ->where('is_delete', '=', '0')
            ->group('log_type')
            ->select();
        return $list;
    }

    /**
     * 获取所有列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getAllList($param = [])
    {
        // 查询模型
        $query = $this->getNewQuery();
        // 查询参数
        $filter = $this->getQueryFilter($param);
        // 查询列表记录
        $list = $query
            ->with(['admin_user'])
            ->where($filter)
            ->where('is_delete', '=', '0')
            ->order(['create_time' => 'desc'])
            ->select();
        return $list;
    }

    public function getQueryFilter($param)
    {
        $params = $this->setQueryDefaultValue($param, [
            'search' => '',
        ]);

        $filter = [];
        !empty($params['search']) && $filter[] = ["log_type", "like", "%{$params['search']}%"];

        if (!empty($params['create_time'])) {
            $times = between_time($params['create_time']);
            $filter[] = ['create_time', '>=', $times['start_time']];
            $filter[] = ['create_time', '<', $times['end_time'] + 86400];
        }
        return $filter;
    }

    /**
     * 记录日志
     * @return array|false
     */
    public static function recordLog($type, $information, $adminUserId)
    {
        $data = [
            'log_type' => $type,
            'log_information' => $information,
            'admin_user_id' => $adminUserId,
        ];
        return (new static)->save($data);
    }


    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->save(['is_delete' => 1]);
    }

    /**
     * 批量软删除
     * @return false|int
     */
    public function batchSetDelete($ids)
    {
        return $this->where($this->getPk(), 'in', $ids)->save(['is_delete' => 1]);
    }
}
